#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <poll.h>
#include <errno.h>

#define CAN0_INTERFACE    "can0"
#define CAN1_INTERFACE    "can1"
#define TEST_CAN_ID       0x101

#define TIMEOUT_MS        2000

typedef struct {
    int sockfd;
    char *ifname;
    struct can_frame tx_frame;
} CanChannel;


void test_can_open()
{
    char cmd[100];
    int i = 10;
    printf("打开can0!\n");
    snprintf(cmd, sizeof(cmd), "ifconfig can0 down;ip link set can0 type can bitrate 500000;ifconfig can0 up\n");
    system(cmd);
    printf("打开can1!\n");
    memset( cmd, 0, sizeof(cmd) );
    snprintf(cmd, sizeof(cmd), "ifconfig can1 down;ip link set can1 type can bitrate 500000;ifconfig can1 up\n");
    system(cmd);
}

int test_can_bus(int cmd_fd) 
{
    struct ifreq ifr;
    struct sockaddr_can addr;
    CanChannel channels[2] = {
        { .ifname = CAN0_INTERFACE },
        { .ifname = CAN1_INTERFACE }
    };
    test_can_open();
    for (int i=0; i<2; i++) 
    {
        // 创建 Socket
        if ((channels[i].sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
            perror("Socket creation failed");
            return 1;
        }
        // 指定 CAN 接口名称
        strcpy(ifr.ifr_name, channels[i].ifname);
        ioctl(channels[i].sockfd, SIOCGIFINDEX, &ifr);

        // 绑定 Socket 到 CAN 接口
        addr.can_family = AF_CAN;
        addr.can_ifindex = ifr.ifr_ifindex;
        if (bind(channels[i].sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
            perror("套接字绑定失败");
            close(channels[i].sockfd);
            return 1;
        }

        
        channels[i].tx_frame.can_id = TEST_CAN_ID + i;
        channels[i].tx_frame.can_dlc = 8;
        for( int j=0; j<8; j++ )
        {
            channels[i].tx_frame.data[j] = j+i*10;
        }
        usleep(500000);
    }
    
    int bytes_sent;
    for (int i=0; i<2; i++) 
    {
        bytes_sent = write(channels[i].sockfd, &channels[i].tx_frame, sizeof(struct can_frame));
        if( bytes_sent  != sizeof(struct can_frame) ) 
        {
            perror("发送失败");
            close(channels[i].sockfd);
            return 1;
        } 

        printf("[测试工装] 已发送 CAN%d 数据: ID=0x%08x, 数据=", i, channels[i].tx_frame.can_id );
        for( int j=0; j<8; j++ )
        {
                printf( "0x%02X ",channels[i].tx_frame.data[j] );
        }
        printf("\n");
        usleep(50000);
    }
    usleep(500000);
    recv_tcp_data_discard( cmd_fd, 1 );
    for (int i=0; i<2; i++) 
    {
        struct can_frame rx_frame;
        int nbytes = read(channels[i].sockfd, &rx_frame, sizeof(struct can_frame));
        if (nbytes < 0) {
            perror("read 失败");
            printf("[测试工装] ❌ CAN%d 测试失败!\n");
            close(channels[i].sockfd);
            continue;
        }
        printf("收到响应: ID=0x%08X 数据=", rx_frame.can_id);
        for( int j=0; j<8; j++ )
        {
            printf( "0x%02X ",rx_frame.data[j] );
        }
        printf("\n");

        if (rx_frame.can_id == channels[i].tx_frame.can_id && memcmp(rx_frame.data, channels[i].tx_frame.data, 8) == 0) 
        {
            printf("[测试工装] ✅ CAN%d 测试通过!\n", i, rx_frame.data);
        } 
        else 
        {
            printf("[测试工装] ❌ CAN%d 测试失败,数据不匹配! 期望ID=0x%08X 实际ID=0x%08X\n", i, channels[i].tx_frame.can_id, rx_frame.can_id);
            
        }
        usleep(50000);
    }
    printf("\n");
    
    for (int i=0; i<2; i++) {
        close(channels[i].sockfd);
    }
    
    return EXIT_SUCCESS;
}
// int test_can_bus() {
//     struct ifreq ifr;
//     struct sockaddr_can addr;
//     CanChannel channels[2] = {
//         { .ifname = CAN0_INTERFACE },
//         { .ifname = CAN1_INTERFACE }
//     };
    
//     // 初始化所有CAN通道
//     test_can_open();
//     for (int i = 0; i < 2; i++) {
//         if ((channels[i].sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
//             perror("Socket creation failed");
//             goto cleanup;
//         }
        
//         strcpy(ifr.ifr_name, channels[i].ifname);
//         if (ioctl(channels[i].sockfd, SIOCGIFINDEX, &ifr) < 0) {
//             perror("IOCTL failed");
//             goto cleanup;
//         }

//         addr.can_family = AF_CAN;
//         addr.can_ifindex = ifr.ifr_ifindex;
//         if (bind(channels[i].sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
//             perror("套接字绑定失败");
//             goto cleanup;
//         }

//         channels[i].tx_frame.can_id = TEST_CAN_ID + i;
//         channels[i].tx_frame.can_dlc = 8;
//         for (int j = 0; j < 8; j++) {
//             channels[i].tx_frame.data[j] = j + i * 10;
//         }
//     }
//     usleep(500000);

//     const char* test_rounds[] = {"First", "Second", "Third"};
//     printf("\n");
//     // 执行三轮测试
//     for (int round = 0; round < 3; round++) {
//         // 发送阶段
//         for (int i = 0; i < 2; i++) {
//             ssize_t bytes_sent = write(channels[i].sockfd, &channels[i].tx_frame, 
//                                       sizeof(struct can_frame));
//             if (bytes_sent != sizeof(struct can_frame)) {
//                 perror("发送失败");
//                 goto cleanup;
//             }

//             printf("[测试端] %s 已发送 CAN%d 数据: ID=0x%08x, 数据=", 
//                    test_rounds[round], i, channels[i].tx_frame.can_id);
//             for (int j = 0; j < 8; j++) {
//                 printf("0x%02X ", channels[i].tx_frame.data[j]);
//             }
//             printf("\n");
//             usleep(50000);
//         }

//         // 接收阶段
//         for (int i = 0; i < 2; i++) {
//             struct can_frame rx_frame;
//             int nbytes = read(channels[i].sockfd, &rx_frame, sizeof(rx_frame));
//             if (nbytes < 0) {
//                 perror("read 失败");
//                 printf("[测试端] ❌ CAN%d 测试失败!\n", i);
//                 continue;
//             }

//             printf("收到响应: ID=0x%08X 数据=", rx_frame.can_id);
//             for (int j = 0; j < 8; j++) {
//                 printf("0x%02X ", rx_frame.data[j]);
//             }
//             printf("\n");

//             if (rx_frame.can_id == channels[i].tx_frame.can_id && 
//                 memcmp(rx_frame.data, channels[i].tx_frame.data, 8) == 0) {
//                 printf("[测试端] ✅ CAN%d 测试通过!\n", i);
//             } else {
//                 printf("[测试端] ❌ CAN%d 测试失败,数据不匹配! "
//                        "期望ID=0x%08X 实际ID=0x%08X\n", 
//                        i, channels[i].tx_frame.can_id, rx_frame.can_id);
//             }
//             usleep(50000);
//         }
//         printf("\n");
//     }

// cleanup:
//     // 清理资源
//     for (int i = 0; i < 2; i++) {
//         if (channels[i].sockfd >= 0) {
//             close(channels[i].sockfd);
//         }
//     }
    
//     return EXIT_SUCCESS;
// }

